import util from 'util';
import { DatabaseManager } from "./databaseManager";
import path from "path";
import { Options } from 'sequelize'
import logger from "../utils/logger";

let databaseManager: DatabaseManager = null;
const initDbPool = async () => {
    logger.info('========== init database begin ===========')
    if (databaseManager) {
        return databaseManager;
    }
    const logging = (...content) => {
        if (util.inspect(content[content.length - 1].model, { depth: null, compact: true }) !== 'Log') {
            // logger.sql(content[0]) // 打印sql
        }
    };
    const dataSource = global.config.get('dataSource').map(e => ({ ...e, logging }));
    databaseManager = Object.freeze(DatabaseManager.getInstance(dataSource));
    if (dataSource.length > 1) {
        const modelsPath: string[] = Array.prototype.map.call(databaseManager.getDbConfigs(), (e: Options) => path.resolve(__dirname, e.modelPath));
        await databaseManager.initDbInstances(modelsPath);
    } else {
        await databaseManager.initDbInstance(path.resolve(__dirname, dataSource[0].modelPath));
    }
    logger.info('========== init database success ===========');
    return databaseManager;
};
export default initDbPool;